<!DOCTYPE html>
<html lang="zh-CN">

<head>
  <title>AI学习助手 | BCIT</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <!-- Bootstrap 5 -->
  <link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.3.3/css/bootstrap.min.css" rel="stylesheet">

  <style>
    :root {
      --primary-gradient: linear-gradient(135deg, #6366f1 0%, #a855f7 100%);
      --ai-bg: rgba(255, 255, 255, 0.98);
      --shadow-lg: 0 8px 30px rgba(0, 0, 0, 0.12);
      --radius-xl: 1.5rem;
    }

    body {
      background: #f8fafc;
      min-height: 100vh;
      font-family: 'Segoe UI', system-ui, sans-serif;
    }

    /* 主容器 */
    .main-container {
      display: flex;
      flex-direction: column;
      height: 100vh;
      padding: 1rem;
    }

    /* 聊天容器 */
    .chat-wrapper {
      flex: 1;
      background: var(--ai-bg);
      backdrop-filter: blur(10px);
      border-radius: var(--radius-xl);
      box-shadow: var(--shadow-lg);
      margin: 1rem 0;
      border: 1px solid rgba(255, 255, 255, 0.3);
      display: flex;
      flex-direction: column;
    }

    /* 消息区域 */
    #chatHistory {
      flex: 1;
      overflow-y: auto;
      padding: 1.5rem;
      scroll-behavior: smooth;
    }

    /* 消息气泡 */
    .message-bubble {
      max-width: 75%;
      padding: 1.25rem 1.75rem;
      margin: 1rem 0;
      border-radius: var(--radius-xl);
      position: relative;
      animation: messageAppear 0.4s cubic-bezier(0.18, 0.89, 0.32, 1.28);
    }

    .user-message {
      background: var(--primary-gradient);
      color: white;
      margin-left: auto;
      box-shadow: 0 4px 15px rgba(99, 102, 241, 0.2);
    }

    .ai-message {
      background: var(--ai-bg);
      color: #1e293b;
      margin-right: auto;
      border: 1px solid #e2e8f0;
      box-shadow: 0 4px 15px rgba(0, 0, 0, 0.05);
    }

    /* 输入容器 */
    .input-container {
      padding: 1.5rem;
      border-top: 1px solid rgba(0, 0, 0, 0.05);
      background: rgba(255, 255, 255, 0.9);
    }

    #userInput {
      width: 100%;
      min-height: 56px;
      max-height: 150px;
      padding: 1rem 4.5rem 1rem 1.5rem;
      border: 2px solid #e0e0e0;
      border-radius: 1rem;
      font-size: 1rem;
      line-height: 1.5;
      resize: none;
      transition: all 0.3s ease;
    }

    #userInput:focus {
      border-color: #6366f1;
      box-shadow: 0 0 0 3px rgba(99, 102, 241, 0.2);
    }

    /* 发送按钮 */
    #sendButton {
      position: absolute;
      right: 1rem;
      bottom: 1rem;
      width: 48px;
      height: 48px;
      border-radius: 50%;
      background: var(--primary-gradient);
      border: none;
      transition: all 0.3s ease;
    }

    /* 加载指示器 */
    .loading-indicator {
      position: fixed;
      bottom: 100px;
      left: 50%;
      transform: translateX(-50%);
      background: white;
      padding: 0.8rem 2rem;
      border-radius: 2rem;
      box-shadow: var(--shadow-lg);
      display: none;
    }

    @keyframes messageAppear {
      from {
        opacity: 0;
        transform: translateY(20px) scale(0.95);
      }

      to {
        opacity: 1;
        transform: translateY(0) scale(1);
      }
    }

    @media (max-width: 768px) {
      .main-container {
        padding: 0.5rem;
      }

      .message-bubble {
        max-width: 85%;
        padding: 1rem;
      }

      #userInput {
        padding-right: 3.5rem;
      }

      #sendButton {
        width: 40px;
        height: 40px;
        right: 0.75rem;
        bottom: 0.75rem;
      }
    }
  </style>
</head>

<body>
  <nav id="navbarPlaceholder"></nav>

  <div class="main-container">
    <div class="chat-wrapper">
      <!-- 聊天历史记录 -->
      <div id="chatHistory">
        <div class="message-bubble ai-message">
          <div class="d-flex align-items-start gap-2">
            <div class="badge bg-primary rounded-pill p-2">🎓</div>
            <div>
              <div class="fw-semibold mb-2">学习助手</div>
              您好！我是您的智能学习伙伴，随时为您解答问题
            </div>
          </div>
        </div>
      </div>

      <!-- 输入区域 -->
      <div class="input-container position-relative">
        <textarea id="userInput" class="form-control" placeholder="输入您的问题，Shift+Enter换行..." rows="1"></textarea>
        <button class="btn btn-primary" id="sendButton">
          <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" fill="currentColor" viewBox="0 0 16 16">
            <path
              d="M15.854.146a.5.5 0 0 1 .11.54l-5.819 14.547a.75.75 0 0 1-1.329.124l-3.178-4.995L.643 7.184a.75.75 0 0 1 .124-1.33L15.314.037a.5.5 0 0 1 .54.11zM6.636 10.07l2.761 4.338L14.13 2.576zm6.787-8.201L1.591 6.602l4.339 2.76z" />
          </svg>
        </button>
      </div>
    </div>

    <div class="loading-indicator" id="loadingIndicator">
      <div class="spinner-border spinner-border-sm text-primary"></div>
      <span class="ms-2">AI正在思考中...</span>
    </div>
  </div>

  <nav id="footerPlaceholder"></nav>

  <!-- 脚本 -->
  <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
  <script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.3.3/js/bootstrap.bundle.min.js"></script>

  <script>
    // 安全警告：实际部署时务必使用后端代理
    const API_CONFIG = {
      endpoint: 'https://api.deepseek.com/v1/chat/completions', // 确认V3接口地址
      headers: {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer sk-4654c1c8fc534041ac4559709e305d30' // 临时测试用，生产环境必须移除
      }
    };

    // 增强的API请求处理
    async function sendMessage() {
      const input = userInput.val().trim();
      if (!input) {
        userInput.addClass('animate__shakeX');
        setTimeout(() => userInput.removeClass('animate__shakeX'), 500);
        return;
      }

      // 输入验证
      if (input.length > 1000) {
        alert('问题内容不能超过1000字符');
        return;
      }

      const $userMessage = createMessage(input, true);
      $('#chatHistory').append($userMessage);
      userInput.val('').height('auto');

      try {
        $('#loadingIndicator').fadeIn(200);
        $('#sendButton').prop('disabled', true);

        // 根据DeepSeek文档调整请求格式
        const response = await fetch(API_CONFIG.endpoint, {
          method: 'POST',
          headers: API_CONFIG.headers,
          body: JSON.stringify({
            model: "deepseek-chat",      // 确认模型名称
            messages: [{
              role: "user",
              content: input
            }],
            temperature: 0.7,
            max_tokens: 500,              // 添加必要参数
            stream: false,                // 关闭流式传输
            frequency_penalty: 0.5       // 根据文档添加参数
          })
        });

        // 增强错误处理
        if (!response.ok) {
          const errorData = await response.json();
          throw new Error(`API错误: ${errorData.error?.message || response.statusText}`);
        }

        const data = await response.json();
        if (!data.choices?.[0]?.message?.content) {
          throw new Error('无效的响应格式');
        }

        const $aiMessage = createMessage(data.choices[0].message.content, false);
        $('#chatHistory').append($aiMessage);

      } catch (error) {
        console.error('请求失败:', error);
        const errorMsg = error.message.includes('401') ? '认证失败，请检查API Key'
          : error.message.includes('429') ? '请求过于频繁'
            : '服务暂时不可用';
        const $errorMessage = createMessage(`⚠️ ${errorMsg}`, false);
        $('#chatHistory').append($errorMessage);
      } finally {
        $('#loadingIndicator').fadeOut(200);
        $('#sendButton').prop('disabled', false);
        $('#chatHistory').scrollTop($('#chatHistory')[0].scrollHeight);
      }
    }

    // 创建消息元素
    function createMessage(content, isUser = true) {
      const timestamp = new Date().toLocaleTimeString('zh-CN', {
        hour: '2-digit',
        minute: '2-digit'
      });

      return $(`
                <div class="message-bubble ${isUser ? 'user-message' : 'ai-message'}">
                    <div class="d-flex align-items-start gap-3">
                        ${!isUser ?
          `<div class="badge bg-primary rounded-pill p-2">🤖</div>` :
          `<div class="badge bg-white rounded-pill p-2">👤</div>`
        }
                        <div>
                            <div class="d-flex justify-content-between align-items-center mb-2">
                                <div class="fw-semibold">${isUser ? '您' : '学习助手'}</div>
                                <small class="text-muted">${timestamp}</small>
                            </div>
                            <div class="message-content">${content}</div>
                        </div>
                    </div>
                </div>
            `);
    }

    // 输入框交互
    const userInput = $('#userInput');

    // 动态高度调整
    userInput.on('input', function () {
      this.style.height = 'auto';
      this.style.height = Math.min(this.scrollHeight, 150) + 'px';
    });

    // 发送消息
    async function sendMessage() {
      const input = userInput.val().trim();
      if (!input) {
        userInput.addClass('animate__shakeX');
        setTimeout(() => userInput.removeClass('animate__shakeX'), 500);
        return;
      }

      const $userMessage = createMessage(input, true);
      $('#chatHistory').append($userMessage);
      userInput.val('').height('auto');

      try {
        $('#loadingIndicator').fadeIn(200);
        $('#sendButton').prop('disabled', true);

        const response = await fetch(API_CONFIG.endpoint, {
          method: 'POST',
          headers: API_CONFIG.headers,
          body: JSON.stringify({
            model: "deepseek-chat",
            messages: [{ role: "user", content: input }],
            temperature: 0.7
          })
        });

        const data = await response.json();
        const $aiMessage = createMessage(data.choices[0].message.content, false);
        $('#chatHistory').append($aiMessage);
      } catch (error) {
        const $errorMessage = createMessage("⚠️ 服务暂时不可用，请稍后重试", false);
        $('#chatHistory').append($errorMessage);
      } finally {
        $('#loadingIndicator').fadeOut(200);
        $('#sendButton').prop('disabled', false);
        $('#chatHistory').scrollTop($('#chatHistory')[0].scrollHeight);
      }
    }

    // 事件监听
    $('#sendButton').click(sendMessage);
    userInput.keypress(e => {
      if (e.which === 13 && !e.shiftKey) {
        e.preventDefault();
        sendMessage();
      }
    });
  </script>

  <script src="./scripts/skeleton.js"></script>
</body>

</html>
